from datetime import datetime, timedelta
import random
import sys
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import numpy as np

# 导入数据库模型
sys.path.append('.')  # 确保能够导入当前目录的模块
from server import User, GaitData, db, app

def generate_random_gait_data():
    """生成随机的步态数据"""
    stride_length = round(random.uniform(0.5, 1.5), 2)  # 步幅范围：0.5-1.5米
    step_height = round(random.uniform(0.1, 0.3), 2)    # 步高范围：0.1-0.3米
    time_interval = round(random.uniform(0.8, 1.2), 2)  # 时间间隔范围：0.8-1.2秒
    point_count = random.randint(50, 200)               # 点数范围：50-200
    
    # 根据参数确定结果
    if (0.7 <= stride_length <= 1.3 and 
        0.15 <= step_height <= 0.25 and 
        0.9 <= time_interval <= 1.1):
        result = "正常"
    else:
        result = "异常"
        
    return {
        'stride_length': stride_length,
        'step_height': step_height,
        'time_interval': time_interval,
        'point_count': point_count,
        'result': result
    }

def generate_mock_data(num_records=1000):
    """生成模拟数据并存储到数据库"""
    print("开始生成模拟数据...")
    
    with app.app_context():
        try:
            # 确保有默认用户
            default_user = User.query.filter_by(username='admin').first()
            if not default_user:
                print("创建默认管理员用户...")
                from werkzeug.security import generate_password_hash
                default_user = User(
                    username='admin',
                    password=generate_password_hash('admin123'),
                    email='admin@example.com',
                    is_admin=True
                )
                db.session.add(default_user)
                db.session.commit()
            
            # 生成随机的创建时间范围（最近30天内）
            end_date = datetime.now()
            start_date = end_date - timedelta(days=30)
            
            # 批量生成并存储数据
            batch_size = 100  # 每批处理的记录数
            for i in range(0, num_records, batch_size):
                batch_records = []
                for j in range(min(batch_size, num_records - i)):
                    # 生成随机数据
                    data = generate_random_gait_data()
                    
                    # 生成随机创建时间
                    random_timestamp = start_date + timedelta(
                        seconds=random.randint(0, int((end_date - start_date).total_seconds()))
                    )
                    
                    # 创建GaitData记录
                    gait_record = GaitData(
                        user_id=default_user.id,
                        task_id=random.randint(1, 3),  # 随机任务ID（1-3）
                        stride_length=data['stride_length'],
                        step_height=data['step_height'],
                        time_interval=data['time_interval'],
                        point_count=data['point_count'],
                        result=data['result'],
                        created_at=random_timestamp
                    )
                    batch_records.append(gait_record)
                
                # 批量插入数据
                db.session.bulk_save_objects(batch_records)
                db.session.commit()
                
                # 打印进度
                progress = min((i + batch_size) / num_records * 100, 100)
                print(f"进度: {progress:.1f}% ({i + len(batch_records)}/{num_records})")
            
            print(f"成功生成{num_records}条模拟数据!")
            
            # 打印一些统计信息
            total_records = GaitData.query.count()
            normal_records = GaitData.query.filter_by(result="正常").count()
            abnormal_records = GaitData.query.filter_by(result="异常").count()
            
            print("\n数据统计:")
            print(f"总记录数: {total_records}")
            print(f"正常记录: {normal_records} ({normal_records/total_records*100:.1f}%)")
            print(f"异常记录: {abnormal_records} ({abnormal_records/total_records*100:.1f}%)")
            
        except Exception as e:
            print(f"生成数据时出错: {str(e)}")
            db.session.rollback()
            raise

if __name__ == '__main__':
    generate_mock_data(1000) 